package com.xunji.standard.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xunji.standard.common.R;
import com.xunji.standard.entity.CodeBook;
import com.xunji.standard.service.CodeBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: xuqiang_imyours
 * @Date: 2025/8/25 14:20
 * @Description:
 **/
@Slf4j
@Api(tags = "密码本")
@RestController
@RequestMapping("/cd")
public class CodeBookController {
    @Autowired
    private CodeBookService codeBookService;

    /**
     * 分页查询
     *
     * @param current 当前页码
     * @param size    每页大小
     * @return 分页结果
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public R pageQuery(@RequestParam(defaultValue = "1") Long current, @RequestParam(defaultValue = "10") Long size) {
        Page<CodeBook> page = codeBookService.pageQuery(current, size);
        return R.success(page);
    }

    /**
     * 根据ID查询
     *
     * @param id 主键
     * @return CodeBook对象
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询")
    public R getById(@PathVariable String id) {
        return R.success(codeBookService.getById(id));
    }

    /**
     * 新增
     *
     * @param codeBook 实体对象
     * @return 是否成功
     */
    @PostMapping
    @ApiOperation(value = "新增", notes = "新增")
    public R save(@RequestBody CodeBook codeBook) {
        // 检查密码是否已存在
        boolean exists = codeBookService.checkPasswordExists(codeBook.getPassword());
        if (exists) {
            return R.failure("该密码已存在，请勿重复添加");
        }
        codeBookService.save(codeBook);
        codeBookService.updateCache();
        return R.success();
    }

    /**
     * 修改
     *
     * @param codeBook 实体对象
     * @return 是否成功
     */
    @PutMapping
    @ApiOperation(value = "修改", notes = "修改")
    public R update(@RequestBody CodeBook codeBook) {
        codeBookService.updateById(codeBook);
        codeBookService.updateCache();
        return R.success();
    }

    /**
     * 根据ID删除
     *
     * @param id 主键
     * @return 是否成功
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public R delete(@PathVariable String id) {
        codeBookService.removeById(id);
        codeBookService.updateCache();
        return R.success();
    }
}
